package com.zzl.study.auth.security.authentication.context;

import com.zzl.study.auth.utils.JacksonUtils;
import lombok.Data;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority;

/**
 * @author: zhangzl
 * @date: 2024/6/6 19:26
 * @version: 1.0
 * @description: OIDC 权限
 */
@Data
public class OidcAuthority {

    private IdToken idToken;

    private UserInfo userInfo;

    private String authority;

    private Claims attributes;

    public String getAuthority() {
        return this.authority;
    }

    public static OidcUserAuthority toOidcUserAuthority(OidcAuthority oidcAuthority) {
        if (oidcAuthority == null) {
            return null;
        }
        OidcIdToken oidcIdToken = IdToken.to(oidcAuthority.getIdToken());
        OidcUserInfo oidcUserInfo = UserInfo.to(oidcAuthority.getUserInfo());
        return new OidcUserAuthority(oidcAuthority.getAuthority(), oidcIdToken, oidcUserInfo);
    }

    public static OidcAuthority ofOidcUserAuthority(OidcUserAuthority oidcUserAuthority) {
        if (oidcUserAuthority == null) {
            return null;
        }
        OidcAuthority oidcAuthority = new OidcAuthority();
        oidcAuthority.setAuthority(oidcUserAuthority.getAuthority());
        oidcAuthority.setIdToken(IdToken.of(oidcUserAuthority.getIdToken()));
        oidcAuthority.setUserInfo(UserInfo.of(oidcUserAuthority.getUserInfo()));
        oidcAuthority.setAttributes(JacksonUtils.toObject(oidcUserAuthority.getAttributes(), Claims.class));
        return oidcAuthority;
    }

    public static SimpleGrantedAuthority toSimpleGrantedAuthority(OidcAuthority oidcAuthority) {
        if (oidcAuthority == null) {
            return null;
        }
        return new SimpleGrantedAuthority(oidcAuthority.getAuthority());
    }

    public static OidcAuthority ofSimpleGrantedAuthority(SimpleGrantedAuthority simpleGrantedAuthority) {
        if (simpleGrantedAuthority == null) {
            return null;
        }
        OidcAuthority oidcAuthority = new OidcAuthority();
        oidcAuthority.setAuthority(simpleGrantedAuthority.getAuthority());
        return oidcAuthority;
    }

}
